package com.example.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Collections;

/**
 * @ClassName OperationTestAop
 * @Author lys4134
 * @Date 2021/08/20 09:45:07
 * @Description OperationTestAop
 * @Version 1.0
 **/
@Aspect
@Component
public class OperationTestAop {

    private static final Logger logger = LoggerFactory.getLogger(OperationTestAop.class);

    @Pointcut("@annotation(TestAop)")
    public void test(){

    }

    @Around("test()")
    public Object operate(ProceedingJoinPoint point) throws Throwable {


        
        //获取拦截的方法名
        Signature signature = point.getSignature();
        MethodSignature methodSignature = null;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;
        Method method = point.getTarget().getClass().getMethod(methodSignature.getMethod().getName(), methodSignature.getParameterTypes());
        TestAop annotation = method.getAnnotation(TestAop.class);
        String param1 = annotation.param1();
        String param2 = annotation.param2();
        String param3 = annotation.param3();
        logger.info("注解值为：param1 = {}, param2 = {}, param3 = {}", param1, param2, param3);
        Object[] args = point.getArgs();
        Parameter[] parameters = method.getParameters();
        for (int i = 0 ; i< parameters.length; i++){
            logger.info("注解方法上的参数值为：参数名 = {}, 参数类型 = {}, 参数值 = {}", parameters[i].getName(), parameters[i].getParameterizedType().getTypeName(), args[i]);
        }
        Object result = point.proceed();
        logger.info("方法结果为：" + result.toString());
        return result;
    }
}
